package com.ziven.common.widget;

import androidx.annotation.NonNull;

import com.ziven.easygo.util.EasyUtils;
import com.ziven.easygo.util.MapDataProvider;
import com.ziven.easygo.util.Obtain;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Ziven
 */
public final class Singleton {

    private final static MapDataProvider<Class<?>, Object> SINGLETON = MapDataProvider.of(new ConcurrentHashMap<>());

    private Singleton() {}

    @NonNull
    public static <T> T get(@NonNull Class<T> cls) {
        synchronized (SINGLETON) {
            return EasyUtils.newIfNull(
                    EasyUtils.transition(SINGLETON.get(cls)),
                    () -> {
                        T instance = EasyUtils.newInstance(cls);
                        SINGLETON.put(cls, instance);
                        return instance;
                    });
        }
    }

    @NonNull
    public static <T> T get(@NonNull Class<T> cls,
                            @NonNull Obtain<T> obtain) {
        synchronized (SINGLETON) {
            return EasyUtils.newIfNull(
                    EasyUtils.transition(SINGLETON.get(cls)),
                    () -> {
                        T instance = obtain.obtain();
                        SINGLETON.put(cls, instance);
                        return instance;
                    });
        }
    }
}
